package db

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var TablePrefix = "t_"

type DataBaseConfig struct{
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	IP       string `yaml:"ip"`
	Port     string `yaml:"port"`
	Database string `yaml:"database"`
	Driver   string `yaml:"driver"`
}

var DataBaseConfigs = make(map[string]DataBaseConfig)

var engines = make(map[string]*xorm.Engine)

var LogFile *os.File

func Use(name string) *xorm.Engine {
	if _, ok := engines[name]; !ok {
		c, ok := DataBaseConfigs[name]
		if !ok {
			panic("未定义的数据库")
		}
		dsn := fmt.Sprintf("%s:%s@(%s:%s)/%s", c.UserName, c.Password, c.IP, c.Port, c.Database)
		x, err := xorm.NewEngine(c.Driver, dsn)
		if err != nil {
			panic(err)
		}
		x.SetTableMapper(names.NewPrefixMapper(names.SnakeMapper{}, TablePrefix))
		x.SetColumnMapper(names.GonicMapper{})

		logger := log.NewSimpleLogger3(LogFile, name, log.DEFAULT_LOG_FLAG, log.DEFAULT_LOG_LEVEL)
		logger.ShowSQL(true)
		x.SetLogger(logger)

		engines[name] = x
	}
	return engines[name]
}
